package com.ssii.www.myproject.repository;

import com.ssii.www.myproject.query.BaseQuery;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.List;
//使用BaseRepositoryImpl作为我们自定义接口的实现类  1.在Spring中配置
public class BaseRepositoryImpl<T,ID extends Serializable> extends SimpleJpaRepository<T,ID> implements BaseRepository<T,ID> {
  //2.让BaseRepositoryImpl中的EntityManager有值 :用一个来接受
  private EntityManager entityManager;

  public BaseRepositoryImpl(Class<T> domainClass, EntityManager em){
    super(domainClass,em);
    this.entityManager = em;
  }

  @Override
  public Page<T> findPageByQuery(BaseQuery baseQuery) {
    // public PageRequest(int page, int size, Sort sort) {
    PageRequest pageRequest = new PageRequest(baseQuery.getBeginPage(), baseQuery.getPageSize(), baseQuery.createSort());
    //public Page<T> findAll(Specification<T> spec, Pageable pageable) { PageRequest 是Pageable的子类
    Page<T> all = super.findAll(baseQuery.createSpec(), pageRequest);
    return all;
  }

  @Override
  public List<T> findByQuery(BaseQuery baseQuery) {
    // List<T> findAll(Specification<T> var1); 不分页的查询
    return super.findAll(baseQuery.createSpec());
  }

  @Override
  public List<T> findByJpql(String jpql, Object... params) {
    Query query = entityManager.createQuery(jpql);
    //判断
    if (params!=null&&params.length!=0){
      for (int i = 0; i <params.length ; i++) {
        query.setParameter(i+1,params[i]);
      }
    }
    return query.getResultList();
  }
}
